﻿//Copyright 2008 Kristian Gundry And Rune Juhl-Petersen
//This file is part of Plain.

//Plain is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//any later version.

//Plain is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Lesser General Public License for more details.

//You should have received a copy of the GNU Lesser General Public License
//along with Plain.  If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Plain.Mapping;
using System.Collections;

namespace Plain.Web {
    /// <summary>
    /// This boud field lets you bind to fields in lower in the object structure
    /// 
    /// <example>
    /// <plain:PlainBoundField DataField="Category.Name"/>
    /// <!--this binds to the Name property of the Category property-->
    /// </example>
    /// </summary>
    public class PlainBoundField:BoundField {
        protected override void OnDataBindField(object sender, EventArgs e) {
            //get field from dataentity
            object o =PropertyUtil.GetValue<object>(((GridViewRow)((DataControlFieldCell)sender).Parent).DataItem, DataField);
            if (o != null) {
                if (HandleAsList && o is IEnumerable) {
                    StringBuilder sb = new StringBuilder();
                    bool first = true;
                    foreach(object listItem in (IEnumerable)o){
                        if (first) {
                            first = false;
                        } else {
                            sb.Append(SubListDataField);
                        }
                        
                        if (string.IsNullOrEmpty(SubListDataField)) {
                            sb.Append(FormatDataValue(listItem, true));
                        } else {
                            sb.Append(FormatDataValue(PropertyUtil.GetValue<object>(listItem,SubListDataField), true));
                        }
                    }
                    
                    
                }              
            } else {
                ((DataControlFieldCell)sender).Text = "";
            }
        }
        public string DataSeperator { get { return dataSeperator; } set { dataSeperator = value; } }
        private string dataSeperator = ", ";
        public string Func { get; set; }
        public string SubListDataField { get; set; }
        public bool HandleAsList{get;set;}        
        public delegate string DataFormat(object o);
    }
}
